Page({
  request: {},
  data: {
    formData: {},
    addrList: [],
    addrIndexList: [],
    expectDays: [],
    expectDaysIndex: 0,
    estDays: [],
    estDaysIndex: 0,
    verifyCodeList: [],
    exprComList: [],
    exprComListIndex: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.showLoading({
      title: '数据加载中...',
      mask: true
    })

    this.request = require('../../common/networks');
    this.util = require('../../common/util');

    var formData = options.formData ? JSON.parse(options.formData) : {};
    formData.bldLift = "1";
    formData.verify = "0";
    formData.exprStatus = "";
    formData.estDeliverDate = "";

    var expectDays = this.util.getNext15Days();
    var estDays = this.util.getNextSevenDays();
    this.setData({
      expectDays: expectDays,
      expectDaysIndex: 0,
      estDays: estDays,
      estDaysIndex: 0,
      formData: formData
    });
    var page = this;
    this.request.getAddrTreeCascade({}, function(data) {
      var len = data.length;
      var indexList = [0];
      for (var i = 1; i < len; i++) {
        indexList.push(0);
      }
      page.setData({
        addrList: data,
        addrIndexList: indexList
      });

      wx.hideLoading();
    }, function(e) {
      wx.showToast({
        title: 'Sorry，数据加载失败，请刷新重试',
        icon: 'none',
        duration: 3000
      })
      wx.hideLoading();
    });

    this.request.getExpress({}, function(data) {
      page.setData({
        exprComList: data
      });
    }, function() {});

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    wx.setNavigationBarTitle({
      title: '蒲公英家居-创建新订单',
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {},

  bindCstNameInput: function(e) {
    this.data.formData.cstName = e.detail.value;
  },
  bindCstMobileInput: function(e) {
    this.data.formData.cstMobile = e.detail.value;
  },
  onAddrTreeChange: function(e) {
    var addrIndexList = e.detail.value;
    var addrList = this.data.addrList;
    var formData = this.data.formData;
    formData.cstAddrProvCode = addrList[0][addrIndexList[0]].code;
    formData.cstAddrCityCode = addrList[1][addrIndexList[1]].code;
    formData.cstAddrAreaCode = addrList[2][addrIndexList[2]].code;
    formData.cstAddrDistCode = addrList[3][addrIndexList[3]].code;
    var addrTitle = addrList[0][addrIndexList[0]].name;
    if (formData.cstAddrProvCode != formData.cstAddrCityCode) {
      addrTitle += '/' + addrList[1][addrIndexList[1]].name;
    }
    addrTitle += '/' + addrList[2][addrIndexList[2]].name;
    if (formData.cstAddrDistCode != '0') {
      addrTitle += '/' + addrList[3][addrIndexList[3]].name;
    }

    this.setData({
      addrTitle: addrTitle
    });
  },
  onAddrTreeColumnChange: function(e) {
    var column = e.detail.column;
    var columnVal = e.detail.value;
    var page = this;
    var addrList = this.data.addrList;
    if (addrList.length - 1 == column || e.detail.value < 0) {
      return;
    }

    var addrIndexList = this.data.addrIndexList;
    var parentCode = addrList[column][e.detail.value].code;
    this.request.getAddrTreeCascade({
      parentCode: parentCode,
      column: column
    }, function(data) {
      data = data || [];
      addrList.splice(column + 1, addrList.length - (column + 1));
      addrIndexList.splice(column + 1, addrIndexList.length - (column + 1));
      addrIndexList[column] = columnVal;
      for (var i = 0; i < data.length; i++) {
        addrList.push(data[i]);
        addrIndexList.push(0);
      }
      page.setData({
        addrList: addrList,
        addrIndexList: addrIndexList
      });
    }, function() {});
  },
  bindBldFloorInput: function(e) {
    this.data.formData.bldFloor = e.detail.value;
  },
  bindBldLiftChange: function(e) {
    this.setData({
      "formData.bldLift": e.detail.value
    });
  },
  bindExprStatusChange: function(e) {
    this.setData({
      "formData.exprStatus": e.detail.value
    });
  },
  bindExpectDaysChange: function(e) {
    var date = this.data.expectDays[e.detail.value];
    this.setData({
      "formData.cstExpectDeliverDate": date
    });
  },
  bindEstDaysChange: function(e) {
    var date = this.data.expectDays[e.detail.value];
    this.setData({
      "formData.estDeliverDate": date
    });
  },
  bindVerifyInput: function(e) {
    var colIdx = e.currentTarget.dataset.colIdx;
    var rowIdx = e.currentTarget.dataset.rowIdx;
    var items = [];
    var util = this.util;
    this.data.verifyCodeList.forEach(function(item, idx) {
      if (rowIdx == idx) {
        item.values[colIdx] = e.detail.value;
      }

      if (!util.isEmpty(item.values[0])) {
        items.push(item.values[0]);
      }

      if (!util.isEmpty(item.values[1])) {
        items.push(item.values[1]);
      }
    })

    this.data.formData.verifyCode = items.join(",");
  },
  bindVerifyChange: function(e) {
    var vals = e.detail.value;
    if (vals.length == 0) {
      this.setData({
        "formData.verify": "0",
        verifyCodeList: []
      });
      return;
    }
    if (this.data.verifyCodeList.length > 0) {
      this.setData({
        "formData.verify": vals[0]
      });
      return;
    }

    var list = [];
    for (var i = 0; i < 2; i++) {
      list.push({
        id: "v" + 1,
        values: ["", ""]
      });
    }
    this.setData({
      "formData.verify": vals[0],
      verifyCodeList: list
    });
  },
  bindAddVerifyCode: function(e) {
    var list = this.data.verifyCodeList;
    if (list.length >= 5) {
      return;
    }
    list.push({
      id: "v" + 1,
      values: ["", ""]
    });
    this.setData({
      verifyCodeList: list
    });
  },
  bindExprComChange: function(e) {
    var index = e.detail.value;
    this.data.formData.exprComId = this.data.exprComList[index].id;
    this.setData({
      exprComName: this.data.exprComList[index].name
    });
  },
  bindPrepayChange: function(e) {
    var indexs = e.detail.value;
    if (indexs.length == 0) {
      this.data.formData.preFrPay = '0';
    } else {
      this.data.formData.preFrPay = '1';
    }
  },
  bindPkAddrInput: function(e) {
    this.data.formData.pkAddr = e.detail.value;
  },
  bindPkMobileInput: function(e) {
    this.data.formData.pkCctMobile = e.detail.value;
  },
  bindPkgNumInput: function(e) {
    this.data.formData.pkgNum = e.detail.value;
  },
  bindExprNoInput: function(e) {
    this.data.formData.exprOrderNo = e.detail.value;
  },
  bindACstAddrDetailInput: function(e) {
    this.data.formData.cstAddrDetail = e.detail.value;
  },
  bindMemoInput: function(e) {
    this.data.formData.specialReq = e.detail.value;
  },
  bindCreateOrderBtn: function(e) {
    let util = require('../../common/util')
    if (util.isEmpty(this.data.formData.cstName)) {
      util.showToast('请输入客户姓名')
      return
    }

    if (util.isEmpty(this.data.formData.cstMobile)) {
      util.showToast('请输入客户手机号码')
      return
    }

    if (!util.isMobile(this.data.formData.cstMobile)) {
      util.showToast('您填写的客户手机号码是个无效号码');
      return
    }

    if (util.isEmpty(this.data.addrTitle)) {
      util.showToast('请填写客户地址');
      return
    }

    if (util.isEmpty(this.data.formData.cstAddrDetail)) {
      util.showToast('请填写客户详细地址');
      return
    }

    if (this.data.formData.bldLift == '0' && util.isEmpty(this.data.formData.bldFloor)) {
      util.showToast('请填写客户所在楼层');
      return
    }

    if ((this.data.formData.verify == '1' || this.data.formData.verify == '2') && util.isEmpty(this.data.formData.verifyCode)) {
      util.showToast('请填写核销单');
      return
    }

    if (util.isEmpty(this.data.formData.exprStatus)) {
      util.showToast('请选择是否到货');
      return
    }

    if (this.data.formData.exprStatus == '0' && util.isEmpty(this.data.formData.estDeliverDate)) {
      util.showToast('请填写预计到货时间');
      return
    }

    var formData = this.data.formData;
    var params = {
      'data': JSON.stringify(formData)
    }
    wx.showLoading({
      title: '订单创建中...',
      mask: true
    })

    this.request.createOrder(params, function(data) {
      var localOrderList = wx.getStorageSync("orderList") || [];
      var now = new Date();
      localOrderList.push({
        orderNo: data.orderNo,
        cstName: formData.cstName,
        cstMobile: formData.cstMobile,
        createTime: now.getTime()
      });
      wx.setStorageSync("cct", {
        cctName: formData.orderCctName,
        cctMobile: formData.orderCctMobile
      });
      wx.setStorageSync("orderList", localOrderList);
      wx.hideLoading();
      wx.showModal({
        title: '温馨提示',
        content: '您提交的订单已经成功，请耐心等候师傅上门服务',
        showCancel: false,
        success: function(res) {
          wx.navigateBack({
            delta: 2
          })
        }
      })
    }, function(res) {
      util.showToast(res.msg)
    })
  }
})